package org.fatewa.engine.endpoint.hooks.impl;

import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.fatewa.engine.design.hooks.EndpointHooks;
import org.fatewa.engine.endpoint.hooks.EndpointHookInvoker;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.concurrent.CompletableFuture;

/**
 * @author 4everlynn
 */
@Slf4j
@Data
@Accessors(fluent = true, chain = true)
public class BuiltinEndpointHookInvoker implements EndpointHookInvoker {

    /**
     * @param hooks   待执行的 Hook
     * @param context Spring Context
     * @param type    要执行的类型
     */
    @Override
    public void invoke(EndpointHooks hooks, ApplicationContext context, HookType type) {

        // 定义运行逻辑
        Runnable run = () -> {
            switch (type) {
                case BEFORE_CREATE:
                    hooks.beforeCreate(context);
                    break;
                case CREATED:
                    hooks.created(context);
                    break;
                case BEFORE_EXPORT:
                    // 获取请求映射处理器
                    final RequestMappingHandlerMapping requestMappingHandlerMapping =
                            context.getBean(RequestMappingHandlerMapping.class);
                    // 动态接口导出之前
                    hooks.beforeExport(requestMappingHandlerMapping, context);
                    break;
                default:
                    break;
            }
        };

        if (hooks.async()) {
            // 异步执行
            CompletableFuture.runAsync(run);
        } else {
            // 同步执行
            run.run();
        }

    }
}
